package cn.wiseda.finance.shiro;

import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShiroDemo {
    private static final Logger log = LoggerFactory.getLogger("ShiroDemo");

    public static void main(String[] args) {
//        Factory<SecurityManager> factory = new IniSecurityManagerFactory(
//                "H:\\eclipse\\workspace\\finance\\src\\test\\java\\cn\\wiseda\\finance\\shiro\\shiro.ini");
//        SecurityManager sm = factory.getInstance();
//        SecurityUtils.setSecurityManager(sm);
//        Subject subject = SecurityUtils.getSubject();
//
//        UsernamePasswordToken token = new UsernamePasswordToken("wang", "123");
//
//        try {
//            subject.login(token);
//        } catch (AuthenticationException e) {
//            System.out.println(e.getMessage());
//        }
//
//        boolean authenticated = subject.isAuthenticated();
//        System.out.println(authenticated);
//        subject.logout();
        ShiroDemo s = new ShiroDemo();
        s.authLdap();
    }

    public AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
            LdapContextFactory ldapContextFactory) throws NamingException {

        Object principal = token.getPrincipal();
        Object credentials = token.getCredentials();

        log.debug("Authenticating user '{}' through LDAP", principal);

        // //将用户名拼成DN“cn=lisi,ou=产品研发部,ou=研发中心,dc=example,dc=com”
        // principal = getLdapPrincipal(token);
        LdapContext ctx = null;

        ctx = ldapContextFactory.getLdapContext(principal, credentials);
        // context was opened successfully, which means their credentials were valid. Return the AuthenticationInfo:
        // return createAuthenticationInfo(token, principal, credentials, ctx);

        return null;
    }

    public void authLdap() {
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(
                "H:\\eclipse\\workspace\\finance\\src\\test\\java\\cn\\wiseda\\finance\\shiro\\ldap.ini");

        SecurityManager instance = factory.getInstance();

        SecurityUtils.setSecurityManager(instance);
        Subject user = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("p_wangw", "lovelln");

        user.login(token);

        log.info("User is authenticated:  " + user.isAuthenticated());
    }
}
